const setCookieParser = require("set-cookie-parser")
const CommonAxerrHG = require("../../tool/CommonAxerrHandlerGenerator").CommonAxerrHandlerGen;
const SpecialGroup = require("./SpecialGroup").SpecialGroup

class KdocsDrive {
  /**
   * 
   * @param {String} wps_sid 
   */
  constructor(wps_sid) {
    this.wps_sid = wps_sid;
    this.csrf_token = KdocsDrive.CreateCsrfToken();
    this.axios = require("axios").default.create({
      headers: {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.173",
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
        "accept-encoding": "gzip, deflate, br",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
        // "connection": "upgrade",
        // "cache-control": "max-age=0",
        "upgrade-insecure-requests": "1",
        "content-type": "application/json;charset=utf-8",
        'sec-fetch-dest': 'iframe',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'same-origin'
      },
      maxContentLength: Number.MAX_SAFE_INTEGER,
      maxRedirects: 0,
      validateStatus: s => s == 200
    })
    this.__appendCookies = [{
      name: "singleSignStart",
      value: `${Date.now()}`
    }, {
      name: "arrwMore",
      value: "true"
    }, {
      name: "Default",
      value: 'DESC-mtime'
    }];

    this.GetSpecialGroupPromise = this.ONLY_ONCE_getSpecialGroupInfo();

    var wps = this;
    var _doitAfterNew = (function init() {
      wps.axios.get('https://www.kdocs.cn/?show=all', {
        headers: {
          cookie: wps.cookies_as_header
        }
      }).then(axresp => {
        if (axresp.headers
          && axresp.headers["set-cookie"]) {
          let parsed = setCookieParser.parse(axresp.headers["set-cookie"]);
          if (parsed && parsed.length) {
            // debugger
            let hasValue = parsed.filter(e => !!e.value);
            hasValue.forEach(e => {
              wps.__appendCookies.push({
                name: e.name,
                value: e.value
              })
            })
          }
          // debugger
        }
      }).catch(axerr => {
        //DO NOTHING?
      })
    })();
  }

  get cookies_as_header() {
    return `wps_sid=${
      this.wps_sid
      }; csrf=${
      this.csrf_token
      }; ${this.__appendCookies.map(e => `${e.name}=${e.value}`).join("; ")}`
  }

  /**
   * @api private
   * @returns {Promise<{ok:Boolean,msg:String,data:{special_group:SpecialGroup}}>}
   */
  ONLY_ONCE_getSpecialGroupInfo() {
    return new Promise(resolve => {
      this.axios.get('https://www.kdocs.cn/3rd/drive/api/v3/groups/special', {
        headers: {
          cookie: this.cookies_as_header,
          referer: "https://www.kdocs.cn/?show=all"
        }
      }).then(axresp => {
        // debugger
        if (axresp.data
          && axresp.data.group_type == "special"
          && axresp.data.id
          && axresp.data.name) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              // id: axresp.data.id,
              // name: axresp.data.name,
              special_group: new SpecialGroup(this,
                axresp.data.id, axresp.data.name)
            }
          })
        }

        throw axresp.data;
      }).catch(axerr => {
        CommonAxerrHG(resolve)(axerr);
      })
    })
  }



}

/**
 * 
 * @returns {string} 得到一个客户端生成的CSRF TOKEN
 */
KdocsDrive.CreateCsrfToken = function () {
  let e = "";
  for (var n = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678", r = n.length, i = 0; i < 32; i++) {
    e += n.charAt(Math.floor(Math.random() * r));
  }
  return e;
}




module.exports = {
  KdocsDrive: KdocsDrive
}